package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public Boolean QueryDataIxist(String data, Integer type) {
        if (1 != type && 2 != type) {
            throw new LyException(400, "请求参数有误");
        }
        return query()
                .eq(type == 1, "username", data)
                .eq(type == 2, "phone", data)
                .count() == 1;
    }

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;
    private final String KEY_PREFIX = "user:verify:code:";


    @Override
    public void sendVerifyCode(String phone) {
        if (!RegexUtils.isPhone(phone)) {
            throw new LyException(400, "非正常手机号");
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("phone", phone);
        String code = RandomStringUtils.random(6);
        map.put("code", code);
        this.amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, map);

        this.redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);
    }

    @Autowired
    private BCryptPasswordEncoder passwordEncoder; //对密码加盐处理


    @Override
    public void register(User user, String code) {

        String cacheCode = redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());
        if (!StringUtils.equals(code,cacheCode)){
            throw new LyException(400,"验证码错误");

        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));//接收加密后的密码
        save(user);
    }

    @Override
    public UserDTO queryByPhoneAndPassword(String username, String password) {

        User user = this.getOne(new QueryWrapper<User>().eq("username", username));

        if (user == null || passwordEncoder.matches(password,user.getPassword())) {
            throw new LyException(400,"用户名或密码错误");
        }
        return new UserDTO(user);
    }
}
